package com.thesis.manage.service.impl;

import com.google.common.collect.Lists;
import com.thesis.manage.common.mongodb.impl.AbstractMongoServiceImpl;
import com.thesis.manage.domain.Time;
import com.thesis.manage.service.TimeService;
import com.thesis.manage.service.constant.ErrorMessage;
import com.thesis.manage.service.module.vo.TimeVO;
import com.thesis.manage.service.utils.TimeFormat;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author php
 * @date 2018/2/27
 */
@Service
public class TimeServiceImpl extends AbstractMongoServiceImpl<Time> implements TimeService {
    @Override
    protected Class<Time> getEntityClass() {
        return Time.class;
    }

    @Override
    public void save(Time time) {
        Assert.notNull(time, ErrorMessage.OBJECT_NO_INSTANCE);
        Time one = this.findByType(time.getType());
        if (one != null) {
            time.setId(one.getId());
            this.update(time);
        } else {
            this.insert(time);
        }
    }

    @Override
    public List<TimeVO> info() {
        //查找所有信息
        List<Time> all = this.findAll();
        ArrayList<TimeVO> objects = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(all)) {
            TimeVO timeVO;
            for (Time time : all) {
                //对时间信息进行封装
                timeVO = new TimeVO();
                timeVO.setType(time.getType());
                //时间格式化
                List<Date> dates = TimeFormat.formatDate(time.getTimeSlot());
                if (CollectionUtils.isNotEmpty(dates)) {
                    timeVO.setBegin(dates.get(0));
                    timeVO.setEnd(dates.get(1));
                }
                timeVO.setId(time.getId());
                objects.add(timeVO);
            }
        }
        return objects;
    }

    @Override
    public void close(Integer type) {
        Time one = this.findByType(type);
        if (one != null) {
            this.remove(one.getId());
        }
    }

    @Override
    public Time findByType(Integer type) {
        Assert.notNull(type, ErrorMessage.OBJECT_NO_INSTANCE);
        Time t = new Time();
        t.setType(type);
        return this.findByOne(t);
    }

}
